package com.yc.fav.web;


import com.yc.fav.Utils;
import com.yc.fav.entity.User;
import com.yc.fav.service.IUserService;
import com.yc.fav.service.impl.UserServiceImpl;
import com.yc.fav.vo.Result;
import org.springframework.context.ApplicationContext;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/updatePwd")
public class PwdUpdateServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Result result = new Result();

        if(req.getSession().getAttribute("loginedUser")==null){
            result.setCode(0);
            result.setMsg("请先登录系统");
            Utils.print(resp,result);
            return;
        }
        User user = (User) req.getSession().getAttribute("loginedUser");

        // TODO 完成登录功能之后, 请回复这里的代码

////################# 完成登录功能之后删除 #################
//        User user = new User();
//        user.setId(1);
//        user.setName("zm");
//        user.setPwd("123");
////################# 完成登录功能之后删除 #################

        String oldPwd = req.getParameter("oldPwd");
        String newPwd = req.getParameter("newPwd");
        if(!(user.getPwd().equals(oldPwd))){
            result.setCode(-2);
            result.setMsg("原密码错误");
            Utils.print(resp,result);
            return;
        }
        ApplicationContext cxt = (ApplicationContext) this.getServletContext().getAttribute("cxt");
        IUserService dao = cxt.getBean(IUserService
                .class);

        user.setPwd(newPwd);
        boolean state = dao.updateById(user);
        if(state){
            result.setCode(1);
            result.setMsg("修改成功");
            Utils.print(resp,result);
            req.getSession().setAttribute("loginUser",user);
            return;
        }

        result.setCode(0);
        result.setMsg("修改失败，系统繁忙");
        Utils.print(resp,result);

    }
}
